import atexit
import json
import os

DATA_FOLDER = 'data'
SCHEDULE_FILE = f'{DATA_FOLDER}/schedule.json'

os.makedirs(DATA_FOLDER, exist_ok=True)

schedule = []

try:
    with open(SCHEDULE_FILE, 'r') as rf:
        read = rf.read()
        if read != '':
            schedule = json.loads(read)
except IOError:
    with open(SCHEDULE_FILE, 'w') as file:
        json.dump(schedule, file, sort_keys=True, indent=2)


def save_data():
    with open(SCHEDULE_FILE, 'w') as wf:
        json.dump(schedule, wf, sort_keys=True, indent=2)


def add_schedule(time: int, length: float):
    schedule.append(
        {
            'time': time,
            'length': length
        }
    )
    save_data()


def delete_schedule(schedule_id: int) -> int:
    if schedule_id >= len(schedule):
        return -1
    del schedule[schedule_id]
    save_data()
    return 0


def edit_schedule(id: int, time: int, length: float) -> int:
    if id >= len(schedule):
        return -1
    schedule[id] = {
        'time': time,
        'length': length
    }
    save_data()
    return 0
